package com.martin.lib_base.helper

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach

object HeartBeatHelper {

    // 计数
    private var count = 0

    // 回调列表
    private val callBackList = mutableListOf<() -> Unit>()

    // 激活状态
    private var active = true

    fun onCreate(scope: CoroutineScope) {
        flow {
            while (true) {
                delay(1000)
                if (active) {
                    count++
                    emit(count)
                }
            }
        }
            .flowOn(Dispatchers.IO)
            .onEach {
                callBackList.forEach { callBack ->
                    callBack.invoke()
                }
            }
            .flowOn(Dispatchers.Main)
            .launchIn(scope)
    }

    fun start() {
        active = true
    }

    fun stop() {
        active = false
    }

    fun addCallBack(callBack: () -> Unit) {
        callBackList.add(callBack)
    }

    fun removeCallBack(callBack: () -> Unit) {
        callBackList.remove(callBack)
    }

}